package pl.edu.pk.mech.kkbus.controller;

import java.util.Set;
import java.util.logging.Logger;

import javax.validation.ConstraintViolation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pl.edu.pk.mech.kkbus.component.MyValidator;
import pl.edu.pk.mech.kkbus.dto.ContactMessage;
import pl.edu.pk.mech.kkbus.model.ResponseStatus;
import pl.edu.pk.mech.kkbus.service.ContactService;

@Controller
public class ContactController extends RestController {

    private static final Logger log = Logger.getLogger(ContactController.class.getName());
    
    @Autowired
    ContactService contactService;
    
    @Autowired
    MyValidator validatorComponent;
    
    @RequestMapping(value = "/contact/message", method = RequestMethod.POST)
    public @ResponseBody ResponseStatus sendContactMessage(@RequestBody ContactMessage contactMessage) {
    
        boolean validation = true;
        
        Set<ConstraintViolation<ContactMessage>> violations = validatorComponent.
                getValidatorInstance().validate(contactMessage);
        for (ConstraintViolation<ContactMessage> violation : violations) {
            validation = false;
            
            String propertyPath = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            
            log.info(propertyPath + " " + message);
        }
        
        if (validation) {
            boolean result = contactService.sendMessage(contactMessage);
            return (result == true) ? ResponseStatus.SENT : ResponseStatus.ERROR;
        } else {
            return ResponseStatus.ERROR;
        }
    }
}
